package com.ruoyi.common.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class ParamsUtil {


    public static Map<String, Object> handleServletParameter(HttpServletRequest request) {
        Map<String, String[]> parameter = request.getParameterMap();
        Map<String, Object> rParams = new HashMap<String, Object>(0);
        for (Map.Entry<String, String[]> m : parameter.entrySet()) {
            String key = m.getKey();
            String[] obj = parameter.get(key);
            rParams.put(key, (obj.length > 1) ? obj : obj[0]);
        }
        return rParams;
    }

    public static Map<String, Object> parameterConvert(final Map<String, String[]> parameter) {
        Map<String, Object> rParams = new HashMap<String, Object>(0);
        for (Map.Entry<String, String[]> m : parameter.entrySet()) {
            String key = m.getKey();
            Object[] obj = (Object[]) parameter.get(key);
            rParams.put(key, (obj.length > 1) ? obj : obj[0]);
        }
        return rParams;
    }

    public static String getParamter(Map<String, Object> params, String key) {
        Object str = params.get(key);
        return ((str != null) && (str.toString().length() > 0)) ? str.toString() : null;
    }

    public static HttpUtilResult getParamterWithR(Map<String, Object> params, String key, String errorStr) {

        String[] str = (String[]) params.get(key);
        String rStr = ((str != null) && (str.length > 0)) ? str[0] : null;

        if (StringUtils.isEmpty(rStr)) {

            if (StringUtils.isEmpty(errorStr)) {
                return HttpUtilResult.error();
            }
            return HttpUtilResult.error(errorStr);
        }
        return HttpUtilResult.ok(rStr);
    }

    public static String getParamter(Map<String, Object> params, String key, String defaultValue) {
        String value = getParamter(params, key);
        return (null == value) ? defaultValue : value;
    }


    public static Integer getParamterInteger(Map<String, Object> params, String key) {
        if (params.get(key) != null) {

            if (StringUtils.isEmpty(params.get(key).toString()))
                return null;
            if (params.get(key).toString().toLowerCase().equals("true")) {
                return null;
            } else if (params.get(key).toString().toLowerCase().equals("false")) {
                return null;
            }
            return Integer.parseInt(params.get(key).toString());
        } else {
            return null;
        }
    }

    public static Integer getParamterInt(Map<String, Object> params, String key) {
        if (params.get(key) != null) {

            if (StringUtils.isEmpty(params.get(key).toString()))
                return 0;
            if (params.get(key).toString().toLowerCase().equals("true")) {
                return 1;
            } else if (params.get(key).toString().toLowerCase().equals("false")) {
                return 0;
            }

            return Integer.parseInt(params.get(key).toString());
        } else {
            return 0;
        }
    }

    public static Integer getParamterInt(Map<String, Object> params, String key, Integer defaultValue) {
        Integer value = getParamterInt(params, key);
        return (isNullOrEmpty(value)) ? Integer.valueOf(defaultValue) : value;
    }


    public static Double getParamterDouble(Map<String, Object> params, String key) {
        String value = getParamter(params, key);
        return (isNullOrEmpty(value)) ? null : new Double(value);
    }

    public static Double getParamterDouble(Map<String, Object> params, String key, double defaultValue) {
        Double value = getParamterDouble(params, key);
        return (isNullOrEmpty(value)) ? new Double(defaultValue) : value;
    }

    public static Long getParamterLong(Map<String, Object> params, String key) {
        String value = getParamter(params, key);
        return (isNullOrEmpty(value)) ? null : Long.valueOf(value);
    }

    public static Long getParamterLong(Map<String, Object> params, String key, long defaultValue) {
        Long value = getParamterLong(params, key);
        return (isNullOrEmpty(value)) ? Long.valueOf(defaultValue) : value;
    }

    /**
     * 得到Short参数
     *
     * @param params
     * @param key
     * @return
     */
    public static Short getParamterShort(Map<String, Object> params, String key) {
        String value = getParamter(params, key);
        return (isNullOrEmpty(value)) ? null : Short.valueOf(value);
    }

    public static Short getParamterShort(Map<String, Object> params, String key, short defaultValue) {
        Short value = getParamterShort(params, key);
        return (isNullOrEmpty(value)) ? Short.valueOf(defaultValue) : value;
    }

    public static Date getParamterDate(Map<String, Object> params, String key, int formatter) {
        Date date = null;
        Calendar calendar = Calendar.getInstance();
        int year;
        int month;
        int day;
        int hour;
        int min;
        int sec;
        if (params.get(key) != null) {
            String keyValue = params.get(key).toString().trim();
            if (keyValue.indexOf("-") > -1) {
                String[] dateArr;
                String[] timeArr;
                switch (formatter) {
                    case 0:
                        dateArr = keyValue.split("-");
                        year = Integer.parseInt(dateArr[0]);
                        month = Integer.parseInt(dateArr[1]) - 1;
                        day = Integer.parseInt(dateArr[2]);
                        calendar.set(year, month, day);
                        break;
                    case 1:
                        String[] temp = keyValue.split(" ");
                        dateArr = temp[0].split("-");
                        timeArr = temp[1].split(":");
                        year = Integer.parseInt(dateArr[0]);
                        month = Integer.parseInt(dateArr[1]) - 1;
                        day = Integer.parseInt(dateArr[2]);
                        hour = Integer.parseInt(timeArr[0]);
                        min = Integer.parseInt(timeArr[1]);
                        sec = Integer.parseInt(timeArr[2]);
                        calendar.set(year, month, day, hour, min, sec);
                        break;
                    default:
                        break;

                }
            }
        }
        date = calendar.getTime();
        return date;
    }

    public static Date getParamterDate(Map<String, Object> params, String key, String defaultValue, String formatter) {
        String value = getParamter(params, key, StringUtils.isEmpty(defaultValue) ? "1970-01-01" : defaultValue);
        return DateUtils.dateTime(formatter,value);
    }

    @SuppressWarnings("rawtypes")
    public static String convertParams(Map<String, Object> map) {
        Map.Entry entry;
        StringBuilder sbr = new StringBuilder();
        sbr.append("[");
        for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext(); ) {
            entry = (Map.Entry) iterator.next();
            sbr.append("\"" + entry.getKey().toString() + "\"").append(":")
                    .append(null == entry.getValue() ? "\"\"" : ("\"" + entry.getValue().toString() + "\""))
                    .append(iterator.hasNext() ? "," : "");
        }
        sbr.append("]");
        return sbr.toString();

    }

    public static boolean isNullOrEmpty(Object o) {
        return o == null || String.valueOf(o).trim().length() == 0;
    }


    /**
     * 参数组合 body
     *
     * @param request
     * @return
     */
    public static Map<String, String> getParamMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = request.getParameterMap().keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

    //获取header
    public static Map<String, String> getHeaderMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}
